'use strict';
const {
  Model
} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
  class Chapter extends Model {
    /**
     * Helper method for defining associations.
     * This method is not a part of Sequelize lifecycle.
     * The `models/index` file will call this method automatically.
     */
    static associate(models) {
      // 定义与 Course 的关联
      Chapter.belongsTo(models.Course, {
        foreignKey: 'courseId',
        as: 'course'
      });
    }
  }
  Chapter.init({
    courseId: {
      type: DataTypes.INTEGER,
      allowNull: false,
      validate: {
        notNull: {
          msg: '课程id不能为空'
        },
        isInt: {
          msg: '课程id必须是整数'
        },
        async isExist(value) {
          const course = await sequelize.models.Course.findByPk(value);
          if (!course) {
            throw new Error('所选课程不存在');
          }
        }
      }
    },
    title: {
      type: DataTypes.STRING,
      allowNull: false,
      validate: {
        notNull: {
          msg: '章节标题不能为空'
        },
        len: {
          args: [2, 50],
          msg: '章节标题长度必须在2-50个字符之间'
        }
      }
    },
    content: {
      type: DataTypes.TEXT,
      allowNull: false,
      validate: {
        notNull: {
          msg: '章节内容不能为空'
        },
        notEmpty: {
          msg: '章节内容不能为空'
        }
      }
    },
    videoUrl: {
      type: DataTypes.STRING,
      allowNull: true,
      validate: {
        isUrl: {
          msg: '视频链接必须是有效的URL地址'
        }
      }
    },
    rank: {
      type: DataTypes.INTEGER,
      allowNull: false,
      defaultValue: 0,
      validate: {
        isInt: {
          msg: '排序号必须是整数'
        },
        min: {
          args: [0],
          msg: '排序号不能小于0'
        }
      }
    }
  }, {
    sequelize,
    modelName: 'Chapter',
  });
  return Chapter;
};